﻿using System;

using System.Collections.Generic;
using System.ComponentModel; 
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using ScannerApp.ScannerWebserviceWrapper;
using System.Text.RegularExpressions;

using ScannerApp.Utils;
using CodeBetter.Json;

namespace ScannerApp.Forms
{

    public partial class OutStockForm : ScannerBaseForm
    {
        OutStockOrderResult mOrder;
        String mPickListCode=string.Empty;
        private int currentOrderIndex = 1;
        private int currentScanIndex = 1;
        bool mUpdateShelf = false;
        protected bool mInitFinishFlag = false;

        public OutStockForm()
        {
            InitializeComponent();
            
        }

        public override void Init()
        {
            base.Init();
            mCurrentStatus = ScanBarcodeStatus.OutStockCode;
            this.dgOrder.TableStyles.Add(Utils.Utils.GetTableStyle(typeof(MergedOutStockProduct)));
            this.dgScan.TableStyles.Add(Utils.Utils.GetTableStyle(typeof(ScannedOutStockGoods)));
            DispalyMessage("请选择拣货单号");

            BindOrderList();

        }

        public void BindOrderList()
        {
            mInitFinishFlag = false;
            OutStockProductsParameter param = new OutStockProductsParameter();

            String strResult = ScannerWebServiceProxy.Instance.outStockGetList(Converter.Serialize(param));
            BaseResult<OutStockOrderListResult> result = Converter.Deserialize<BaseResult<OutStockOrderListResult>>(strResult);
            if (result.IsSucessful())
            {
                txtScan.DisplayMember = "PickingId";
                txtScan.DataSource = result.ReturnValue.orderList;

            }
            mInitFinishFlag = true;
        }

        public override void AssignControls()
        {
            this.lblMessage = this.labTitle;
            this.txtScanCode = this.txtScan;
            this.lblProductInfo = this.lblScanedInfo;
            this.lblHeaderInfo = this.lblHeader;
        }

        private void BindData(OutStockOrderResult order,string message, int pageSize)
        {
            DispalyMessage(message);
            if (order != null)
            {
                mOrder = order;
                this.mScanProductOrder = order;
                //this.dgOrder.DataSource = Utils.Utils.ConvertListToDataTable(order.GetMergedOutStockProducts());
                //this.dgScan.DataSource = Utils.Utils.ConvertListToDataTable(order.tempDespatchBodyList);
                this.currentOrderIndex = order.OrderPageIndex;
                this.currentScanIndex = order.ScanPageIndex;

                RefreshOrderGrid(Utils.Utils.ConvertListToDataTable(order.GetMergedOutStockProducts()), order.OrderPageIndex, order.OrderTotalPage, pageSize, order.OrderTotalCount);
                RefreshScanGrid(Utils.Utils.ConvertListToDataTable(order.tempDespatchBodyList), order.ScanPageIndex, order.ScanTotalPage, pageSize, order.ScanTotalCount);

            }
            else
            {
                mOrder = null;
                this.mScanProductOrder = null;
                this.dgOrder.DataSource = null;
                this.dgScan.DataSource = null;
            }
        }

        public override void HandleBarCode(string barCode)
        {
            try
            {
                base.HandleBarCode(barCode);

                if (barCode.Equals(string.Empty))
                {
                    return;
                }

                if (mCurrentStatus == ScanBarcodeStatus.OutStockCode)
                {
                    ScanOutStockCode(barCode);
                }
                else if (mCurrentStatus == ScanBarcodeStatus.ProductCode)
                {
                    this.ScanProductCode(barCode, this.mOrder);
                }
                else if (mCurrentStatus == ScanBarcodeStatus.ShelfCode)
                {
                    ScanShelfCode(barCode);
                }
                else if (mCurrentStatus == ScanBarcodeStatus.DeliveryOrderCode)
                {
                    ScanDeliveryOrderCode(barCode);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        protected override void ScanQRCode(string QRcode)
        {
            Regex reg = new Regex("^[0-9a-zA-Z]+$");
            if (QRcode.Length < 15 || QRcode.Length > 20 || !reg.IsMatch(QRcode))
            {
                DispalyMessage("扫描序列号格式不正确.");
                return;
            }

            if (this.mOrder.IsRepeatedScan(QRcode))
            {
                DispalyMessage("此码已经被扫描过了");
                return;
            }

            OutStockSingleProductParameter param = new OutStockSingleProductParameter();
            param.OutStockCode = this.mOrderCode;
            param.PickingListCode = this.mPickListCode;
            param.ProductCode = QRcode;
            param.Quantity = 1;
            param.UpdateShelf = (mUpdateShelf == true) ? 1 : 0;
            param.searchType = 1;

            string strResult = ScannerWebServiceProxy.Instance.outStockSingleProduct(Converter.Serialize(param));
            BaseResult<OutStockOrderResult> result = Converter.Deserialize<BaseResult<OutStockOrderResult>>(strResult);
            if (result.IsSucessful())
            {
                if (result.ReturnValue.HasOrderFinished())
                {
                    BindData(result.ReturnValue, "全部产品已扫描成功,请选择扫描快递单操作.", param.pageSize);
                }
                else
                {
                    BindData(result.ReturnValue, "产品扫描成功.请继续扫描序列号.", param.pageSize);
                }

                //BindData(result.ReturnValue, "产品已扫描成功", param.pageSize);
                this.mCurrentProductQR = QRcode;
            }
            else
            {
                ReturnCode code = (ReturnCode)Enum.Parse(typeof(ReturnCode), result.FailedCode, true);
                if (code == ReturnCode.notMatchShelf)
                {
                    String message = string.Format("这个产品在{0}上，是否继续？", result.Message);
                    if (MessageBox.Show(message, "确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.OK)
                    {
                        mUpdateShelf = true;
                        ScanQRCode(QRcode); 
                        mUpdateShelf = false;
                        return;
                    }
                }
                else
                {
                    DispalyMessage(result.getReturnCodeMessage());
                }
            }
        }
 

        protected override void ScanProductWithQuantity(string productCode, string lot, float quantity)
        {
            OutStockSingleProductParameter param = new OutStockSingleProductParameter();
            param.OutStockCode = this.mOrderCode;
            param.PickingListCode = this.mPickListCode;
            param.ShelfCode = this.mCurrentShelfCode;
            param.InventoryCode = productCode;
            param.Lot = lot;
            param.Quantity = quantity;

            string strResult = ScannerWebServiceProxy.Instance.outStockSingleProduct(Converter.Serialize(param));
            BaseResult<OutStockOrderResult> result = Converter.Deserialize<BaseResult<OutStockOrderResult>>(strResult);
            if (result.IsSucessful())
            {
                if (result.ReturnValue.HasOrderFinished())
                {
                    BindData(result.ReturnValue, "全部产品已扫描成功,请选择扫描快递单操作.", param.pageSize);
                }
                else
                {
                    BindData(result.ReturnValue, "产品扫描成功.请继续扫描一级码或序列号.", param.pageSize);
                }
                this.ClearProductValues();
                mCurrentStatus = ScanBarcodeStatus.ProductCode;
            }
            else
            {
                DispalyMessage(result.getReturnCodeMessage());
            }
        }

        private void ScanShelfCode(string barCode)
        {
            OutStockSingleProductParameter param = new OutStockSingleProductParameter();
            param.OutStockCode = this.mOrderCode;
            param.PickingListCode = this.mPickListCode;
            param.ShelfCode = barCode;
            param.InventoryCode = this.mCurrentProductCode;
            param.Lot = this.mCurrentProductLot;
            param.Quantity = this.mCurrentProductQuantity;
            param.searchType = 1;
            param.currentPage = this.currentOrderIndex;

            string strResult = ScannerWebServiceProxy.Instance.outStockSingleProduct(Converter.Serialize(param));
            BaseResult<OutStockOrderResult> result = Converter.Deserialize<BaseResult<OutStockOrderResult>>(strResult);
            if (result.IsSucessful())
            {
                if (result.ReturnValue.HasOrderFinished())
                {
                    BindData(result.ReturnValue, "全部产品已扫描成功,请选择扫描快递单操作.", param.pageSize);
                }
                else
                {
                    BindData(result.ReturnValue, "产品扫描成功.请继续扫描一级码或序列号.", param.pageSize);
                }

                //BindData(result.ReturnValue, "产品已扫描成功.请扫描产品序列号", param.pageSize);
                this.ClearProductValues();
                mCurrentStatus = ScanBarcodeStatus.ProductCode;
            }
            else
            {
                DispalyMessage(result.getReturnCodeMessage());
            }
        }

        private void ScanOutStockCode(string barCode)
        {
            try
            {
                ClearGridData();

                OutStockProductsParameter param = new OutStockProductsParameter();
                param.OutStockCode = barCode;
                param.currentPage = this.currentOrderIndex;
                param.currentScanPage = this.currentScanIndex;
                param.searchType = 1;

                String strResult = ScannerWebServiceProxy.Instance.outStockOrder(Converter.Serialize(param));
                BaseResult<OutStockOrderResult> result = Converter.Deserialize<BaseResult<OutStockOrderResult>>(strResult);
                if (result.IsSucessful())
                {
                    //if (!result.ReturnValue.IsFinishedStatus())
                    {
                        BindData(result.ReturnValue, "获取数据成功,请扫描产品一级码或序列号.", param.pageSize);
                        this.mPickListCode = barCode;
                        this.mOrderCode = result.ReturnValue.despatchListHeadBean.id.ToString();
                        mCurrentStatus = ScanBarcodeStatus.ProductCode;
                    }
                    ////else
                    //{
                    //    BindData(result.ReturnValue, "此出库单已完成,不能对其操作.请扫描新的出库单");
                    //}
                }
                else
                {
                    BindData(null, "找不到对应的出库单", param.pageSize);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


        private void ScanDeliveryOrderCode(string barCode)
        {
            OutStockAddDeliveryOrderParameter param = new OutStockAddDeliveryOrderParameter();
            param.OutStockCode = this.mOrderCode;
            param.PickingListCode = this.mPickListCode;
            param.DeliveryOrderCode = barCode;

            String strResult = ScannerWebServiceProxy.Instance.outStockAddDeliveryOrder(Converter.Serialize(param));
            BaseResult<OutStockOrderResult> result = Converter.Deserialize<BaseResult<OutStockOrderResult>>(strResult);
            if (result.IsSucessful())
            {
                BindData(result.ReturnValue, "添加快递单成功,请完成装车.", param.pageSize);
            }
            else
            {
                DispalyMessage("添加快递单失败");
            }
        }

        private void menuClear_Click(object sender, EventArgs e)
        {
            if (mOrderCode == string.Empty)
            {
                return;
            }
            OutStockProductsParameter param = new OutStockProductsParameter();
            param.OutStockCode = this.mOrderCode;
            param.PickingListCode = this.mPickListCode;

            String strResult = ScannerWebServiceProxy.Instance.outStockClearScanedProducts(Converter.Serialize(param));
            BaseResult<OutStockOrderResult> result = Converter.Deserialize<BaseResult<OutStockOrderResult>>(strResult);
            if (result.IsSucessful())
            {
                BindData(result.ReturnValue, "已清空扫描的产品", param.pageSize);
            }
            else
            {
                DispalyMessage("清空已扫描产品失败");
            }
        }

        private void menuDelete_Click(object sender, EventArgs e)
        {
            if (this.dgScan.CurrentRowIndex < 0)
            {
                MessageBox.Show("请选择一条已扫描的记录");
            }
            else
            {
                int num = this.dgScan.CurrentRowIndex;
                string productCode = this.mOrder.tempDespatchBodyList[num].id.ToString();
                OutStockSingleProductParameter param = new OutStockSingleProductParameter();
                param.OutStockCode = this.mOrderCode;
                param.PickingListCode = this.mPickListCode;
                param.ProductCode = productCode;
                param.searchType = 1;
                string strResult = ScannerWebServiceProxy.Instance.outStockCancelSingleProduct(Converter.Serialize(param));
                BaseResult<OutStockOrderResult> result = Converter.Deserialize<BaseResult<OutStockOrderResult>>(strResult);
                if (result.IsSucessful())
                {
                    BindData(result.ReturnValue, "已取消选定数据", param.pageSize);
                }
                else
                {
                    DispalyMessage("产品未能取消");
                }

            }
        }

        private void menuComplete_Click(object sender, EventArgs e)
        {


            //judge if all the products has been scannned. 
            if (!this.mOrder.HasOrderFinished())
            {
                DispalyMessage("此订单未全部扫描.");
                return;
            }
            if (this.mOrder.payComplete == 0)
            {
                DispalyMessage("此订单未付款!");
                return;
            }

            if (String.IsNullOrEmpty(this.mOrder.despatchListHeadBean.expressNo))
            {
                DispalyMessage("尚未扫描快递单号，请选择扫描快递单操作");
                return;
            }

            OutStockProductsParameter param = new OutStockProductsParameter();
            param.OutStockCode = this.mOrderCode;
            param.PickingListCode = this.mPickListCode;

            String strResult = ScannerWebServiceProxy.Instance.outStockFinishOrder(Converter.Serialize(param));
            BaseResult<OutStockOrderResult> result = Converter.Deserialize<BaseResult<OutStockOrderResult>>(strResult);
            if (result.IsSucessful())
            {
                BindData(result.ReturnValue, "装车完成成功,此出库单已关闭.", param.pageSize);
                this.BindOrderList();
                mCurrentStatus = ScanBarcodeStatus.OutStockCode;
            }
            else
            {
                DispalyMessage(result.getReturnCodeMessage());
            }
        }

        private void menuItemCheck_Click(object sender, EventArgs e)
        {
            if (mOrderCode == string.Empty)
            {
                return;
            }

            if (this.mOrder.payComplete == 0)
            {
                DispalyMessage("此订单未付款!");
                return;
            }


            //judge if all the products has been scannned. 
            if (!this.mOrder.HasOrderFinished())
            {
                DispalyMessage("此订单未全部扫描.");
                return;
            }

            OutStockProductsParameter param = new OutStockProductsParameter();
            param.OutStockCode = this.mOrderCode;
            param.PickingListCode = this.mPickListCode;

            String strResult = ScannerWebServiceProxy.Instance.outStockProducts(Converter.Serialize(param));
            BaseResult<OutStockOrderResult> result = Converter.Deserialize<BaseResult<OutStockOrderResult>>(strResult);
            if (result.IsSucessful())
            {
                BindData(result.ReturnValue, "复核成功,此订单已付款.请扫描快递单号", param.pageSize);
                this.mCurrentStatus = ScanBarcodeStatus.DeliveryOrderCode;
            }
            else
            {
                DispalyMessage("result.getReturnCodeMessage()");
            }
        }

        private void menuDeliveryOrder_Click(object sender, EventArgs e)
        {
            if (mOrderCode == string.Empty)
            {
                return;
            }

            if (this.mOrder.payComplete == 0)
            {
                DispalyMessage("此订单未付款!");
                return;
            }


            //judge if all the products has been scannned. 
            if (!this.mOrder.HasOrderFinished())
            {
                DispalyMessage("此订单未全部扫描.");
                return;
            }

            OutStockProductsParameter param = new OutStockProductsParameter();
            param.OutStockCode = this.mOrderCode;
            param.PickingListCode = this.mPickListCode;

            String strResult = ScannerWebServiceProxy.Instance.outStockProducts(Converter.Serialize(param));
            BaseResult<OutStockOrderResult> result = Converter.Deserialize<BaseResult<OutStockOrderResult>>(strResult);
            if (result.IsSucessful())
            {
                BindData(result.ReturnValue, "此订单已付款.请扫描快递单号", param.pageSize);
                this.mCurrentStatus = ScanBarcodeStatus.DeliveryOrderCode;
            }
            else
            {
                DispalyMessage(result.getReturnCodeMessage());
            }
        }

        private void txtScan_KeyPress(object sender, KeyPressEventArgs e)
        {
            this.HandleKeyPress(e);
        }

        private void menuRefresh_Click(object sender, EventArgs e)
        {
            if (mOrderCode == string.Empty)
            {
                return;
            }
            OutStockProductsParameter param = new OutStockProductsParameter();
            param.OutStockCode = this.mPickListCode;
            param.currentPage = this.currentOrderIndex; 
            param.currentScanPage = this.currentScanIndex;
            param.searchType = 1;

            String strResult = ScannerWebServiceProxy.Instance.outStockOrder(Converter.Serialize(param));
            BaseResult<OutStockOrderResult> result = Converter.Deserialize<BaseResult<OutStockOrderResult>>(strResult);
            if (result.IsSucessful())
            {
                BindData(result.ReturnValue, "数据已刷新", param.pageSize);
            }
        }

        private void txtScan_SelectedValueChanged(object sender, EventArgs e)
        {
            if (mInitFinishFlag == false)
            {
                return;
            }

            this.ScanOutStockCode(this.txtScan.Text);

        }

        private void ClearGridData()
        {
            DisplayScannedCode("");
            DispalyMessage("");
            this.currentOrderIndex = 1;
            this.currentScanIndex = 1;
            this.dgOrder.DataSource = null;
            this.dgScan.DataSource = null;
            lbOrderPagination.Text = String.Empty;
            lbScanPagination.Text = String.Empty;
            btnNext.Visible = false;
            btnPrev.Visible = false;
            btnScanNext.Visible = false;
            btnScanPrev.Visible = false;

        }

        private void RefreshOrderGrid(DataTable dataTable, int pageIndex, int totalPage, int pageSize, int totalCount)
        {
            this.dgOrder.DataSource = dataTable;
            if (this.currentOrderIndex == 1)
            {
                this.btnPrev.Enabled = false;
            }
            else
            {
                this.btnPrev.Enabled = true;
            }

            if (this.currentOrderIndex == totalPage)
            {
                this.btnNext.Enabled = false;
            }
            else
            {
                this.btnNext.Enabled = true;
            }
            this.lbOrderPagination.Text = "第" + pageIndex + "/" + totalPage + "页," + "每页" + pageSize + "条," + "共" + totalCount + "条";
            this.btnPrev.Visible = true;
            this.btnNext.Visible = true;
        }

        private void RefreshScanGrid(DataTable dataTable, int pageIndex, int totalPage, int pageSize, int totalCount)
        {
            this.dgScan.DataSource = dataTable;

            if (this.currentScanIndex == 1)
            {
                this.btnScanPrev.Enabled = false;
            }
            else
            {
                this.btnScanPrev.Enabled = true;
            }

            if (this.currentScanIndex == totalPage)
            {
                this.btnScanNext.Enabled = false;
            }
            else
            {
                this.btnScanNext.Enabled = true;
            }
            this.lbScanPagination.Text = "第" + pageIndex + "/" + totalPage + "页," + "每页" + pageSize + "条," + "共" + totalCount + "条";
            this.btnScanPrev.Visible = true;
            this.btnScanNext.Visible = true;
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            this.currentOrderIndex++;
            despatchBodyListPagination();

        }

        private void btnPrev_Click(object sender, EventArgs e)
        {
            this.currentOrderIndex--;
            despatchBodyListPagination();
        }

        private void btnScanPrev_Click(object sender, EventArgs e)
        {
            this.currentScanIndex--;
            tempDespatchListScannerPagination();

        }

        private void btnScanNext_Click(object sender, EventArgs e)
        {
            this.currentScanIndex++;
            tempDespatchListScannerPagination();

        }

        private void despatchBodyListPagination()
        {
            try
            {
                OutStockProductsParameter param = new OutStockProductsParameter();
                param.currentPage = this.currentOrderIndex;
                param.searchType = 2;
                param.OutStockCode = txtScan.Text;
               
                String strResult = ScannerWebServiceProxy.Instance.outStockOrder(Converter.Serialize(param));
                BaseResult<OutStockOrderResult> result = Converter.Deserialize<BaseResult<OutStockOrderResult>>(strResult);
                if (result.IsSucessful())
                {
                    this.currentOrderIndex = result.ReturnValue.OrderPageIndex;

                    RefreshOrderGrid(Utils.Utils.ConvertListToDataTable(result.ReturnValue.GetMergedOutStockProducts()), result.ReturnValue.OrderPageIndex
                     , result.ReturnValue.OrderTotalPage, param.pageSize, result.ReturnValue.OrderTotalCount);
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void tempDespatchListScannerPagination()
        {
            try
            {
                OutStockProductsParameter param = new OutStockProductsParameter();
                param.currentScanPage = this.currentScanIndex;
                param.searchType = 3;
                param.OutStockCode = txtScan.Text;

                String strResult = ScannerWebServiceProxy.Instance.outStockOrder(Converter.Serialize(param));
                BaseResult<OutStockOrderResult> result = Converter.Deserialize<BaseResult<OutStockOrderResult>>(strResult);
                if (result.IsSucessful())
                {
                    this.mOrder.tempDespatchBodyList = result.ReturnValue.tempDespatchBodyList;
                    this.currentScanIndex = result.ReturnValue.ScanPageIndex;
                    RefreshScanGrid(Utils.Utils.ConvertListToDataTable(result.ReturnValue.tempDespatchBodyList), result.ReturnValue.ScanPageIndex
                    , result.ReturnValue.ScanTotalPage, param.scanPageSize, result.ReturnValue.ScanTotalCount);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}